package com.demo.fulllink.api;

import com.demo.fulllink.common.emum.ResponseErrorEnum;
import com.demo.fulllink.common.utils.CommonUtils;
import com.demo.fulllink.mapper.ProductMapper;
import com.demo.fulllink.module.po.ProductPO;
import com.demo.fulllink.module.vo.ResponseVO;
import com.demo.fulllink.service.OrderDBService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/storageapi")
public class ProductAPIController {
    
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    
    @Autowired
    private ProductMapper productMapper;
    
    @Autowired
    private OrderDBService orderDBService;
    
    /**
     * 初始化环境
     *
     * @param productPO
     * @return
     */
    @RequestMapping("/resetenv")
    public ResponseVO resetEnv(@RequestBody ProductPO productPO) {
        if (null != productPO && null != productPO.getId()) {
            ProductPO tmpPo = productMapper.findById(productPO.getId());
            if (null == tmpPo) {
                return ResponseErrorEnum.PRODUCT_NOT_EXIST_ERROR.toResponseVO();
            }
            productMapper.resetStock(productPO);
            cacheProductStock(productPO);
            orderDBService.removeAll();
            return ResponseVO.success(null, "环境初始化成功");
        }
        return ResponseVO.unknown(-1, "环境初始化失败");
    }
    
    /**
     * 缓存库存数据
     *
     * @param productPO
     */
    public void cacheProductStock(ProductPO productPO) {
        String productKey = CommonUtils.getProductStockKey(productPO.getId());
        redisTemplate.delete(productKey);
        redisTemplate.opsForValue().set(productKey, String.valueOf(productPO.getStock()), 30, TimeUnit.MINUTES);
    }
}
